//
//  danmuView.m
//  弹幕
//
//  Created by 宋旭东 on 15/8/7.
//  Copyright (c) 2015年 灵犀一点. All rights reserved.
//

#import "danmuView.h"
#import "danmuItem.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#define kDeviceWidth  [UIScreen mainScreen].bounds.size.width * 0.0625

@interface danmuView ()
{
    float trajectory;
}
@property (strong, nonatomic) NSMutableArray *trajectoryArray2;
@property (strong, nonatomic) NSMutableArray *trajectoryArray3;
@property (strong, nonatomic) NSMutableArray *trajectoryArray4;
@property (strong, nonatomic) NSMutableArray *trajectoryArray5;
@property (strong, nonatomic) NSMutableArray *trajectoryArray6;
@property (strong, nonatomic) NSMutableArray *trajectoryArray7;
@end

@implementation danmuView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        trajectory = self.frame.size.width / 10;
        self.userInteractionEnabled = NO;
        [self initTrajectoryArray];
    }
    return self;
}
- (void)initTrajectoryArray
{
    self.trajectoryArray2 = [[NSMutableArray alloc] init];
    self.trajectoryArray3 = [[NSMutableArray alloc] init];
    self.trajectoryArray4 = [[NSMutableArray alloc] init];
    self.trajectoryArray5 = [[NSMutableArray alloc] init];
    self.trajectoryArray6 = [[NSMutableArray alloc] init];
    self.trajectoryArray7 = [[NSMutableArray alloc] init];
}
- (void)removeTrajectoryarrayAllObject
{
    [_trajectoryArray2 removeAllObjects];
    [_trajectoryArray3 removeAllObjects];
    [_trajectoryArray4 removeAllObjects];
    [_trajectoryArray5 removeAllObjects];
    [_trajectoryArray6 removeAllObjects];
    [_trajectoryArray7 removeAllObjects];
}
- (void)createDanmuItem:(Comment *)content
{
    danmuItem *item = [[danmuItem alloc] initWithFrame:CGRectZero];
    item.content.text = content.comment;
    [item.avatar setImageWithURL:[NSURL URLWithString:content.avatar] placeholderImage:[UIImage imageNamed:@"default_head"]];
    CGSize size = [item.content sizeThatFits:CGSizeMake(5000,kDeviceWidth)];
//    (from + (arc4random() % (to – from + 1)
    int trajectoryCount = (int)2 + (arc4random() % (6 -2+ 1));
    //根据随机数 设置 y
    CGPoint point = [self layoutXandY:size.height trajectoryCount:trajectoryCount];
    item.frame = CGRectMake(point.x, point.y, size.width + size.height + 10, size.height);
    [self addSubview:item];
    //弹幕 item 添加至数组中
    [self trajectoryAddObject:trajectoryCount Object:item];
//    item.layer.position = CGPointMake(point.x, point.y);
    int translationDur = 2 * (item.frame.size.width + item.frame.origin.x ) / (self.frame.size.width / 3);
    CABasicAnimation *translation = [CABasicAnimation animationWithKeyPath:@"position"];
    translation.delegate = self;
    translation.fromValue = [NSValue valueWithCGPoint:item.layer.position];
    translation.toValue = [NSValue valueWithCGPoint:CGPointMake(0 - item.frame.size.width, item.frame.origin.y)];
//     translation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    translation.duration = translationDur;
    translation.repeatCount = 0;
    translation.autoreverses = NO;
    translation.removedOnCompletion = NO;
    translation.fillMode = kCAFillModeForwards;
    [item.layer addAnimation:translation forKey:@"danmu"];
}
- (void)pauseAnimation{
    NSArray *array = self.subviews;
    for (danmuItem *item in array) {
        [self pauseLayer:item.layer];
    }
}
- (void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}
- (void)resumeAnimation
{
    NSArray *array = self.subviews;
    for (danmuItem *item in array) {
        [self resumeLayer:item.layer];
    }
}
- (void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}
- (CGPoint)layoutXandY:(CGFloat)height trajectoryCount:(int)trajectoryCount
{

    float trajectoryY;//弹幕 Y
    float trajectoryX;//弹幕 X
    switch (trajectoryCount) {
        case 2:
            trajectoryY = trajectoryCount *trajectory;
//            判断弹道中有没有弹幕
            if (_trajectoryArray2.count == 0) {
                trajectoryX = self.frame.size.width;
            } else {
                danmuItem *item = (danmuItem *)[_trajectoryArray2 lastObject];
                trajectoryX = item.frame.origin.x + item.frame.size.width + 60;
            }
            break;
        case 3:
            trajectoryY = trajectoryCount *trajectory;
            if (_trajectoryArray3.count == 0) {
                trajectoryX = self.frame.size.width;
            } else {
                danmuItem *item = (danmuItem *)[_trajectoryArray3 lastObject];
                trajectoryX = item.frame.origin.x + item.frame.size.width + 60;
            }
            break;
        case 4:
            trajectoryY = trajectoryCount *trajectory;
            if (_trajectoryArray4.count == 0) {
                trajectoryX = self.frame.size.width;
            } else {
                danmuItem *item = (danmuItem *)[_trajectoryArray4 lastObject];
                trajectoryX = item.frame.origin.x + item.frame.size.width + 60;
            }
            break;
        case 5:
            trajectoryY = trajectoryCount *trajectory;
            if (_trajectoryArray5.count == 0) {
                trajectoryX = self.frame.size.width;
            } else {
                danmuItem *item = (danmuItem *)[_trajectoryArray5 lastObject];
                trajectoryX = item.frame.origin.x + item.frame.size.width + 60;
            }
            break;
        case 6:
            trajectoryY = trajectoryCount *trajectory;
            if (_trajectoryArray6.count == 0) {
                trajectoryX = self.frame.size.width;
            } else {
                danmuItem *item = (danmuItem *)[_trajectoryArray6 lastObject];
                trajectoryX = item.frame.origin.x + item.frame.size.width + 60;
            }
            break;
        case 7:
            trajectoryY = trajectoryCount *trajectory;
            if (_trajectoryArray7.count == 0) {
                trajectoryX = self.frame.size.width;
            } else {
                danmuItem *item = (danmuItem *)[_trajectoryArray7 lastObject];
                trajectoryX = item.frame.origin.x + item.frame.size.width + 60;
            }
            break;
        default:
            break;
    }
    CGPoint point = CGPointMake(trajectoryX, trajectoryY);
    return point;
}
- (void)trajectoryAddObject:(int)trajectoryCount Object:(danmuItem *)object
{
    switch (trajectoryCount) {
        case 2:
            [_trajectoryArray2 addObject:object];
            break;
        case 3:
            [_trajectoryArray3 addObject:object];
            break;
        case 4:
            [_trajectoryArray4 addObject:object];
            break;
        case 5:
            [_trajectoryArray5 addObject:object];
            break;
        case 6:
            [_trajectoryArray6 addObject:object];
            break;
        case 7:
            [_trajectoryArray7 addObject:object];
            break;
        default:
            break;
    }
}
- (void)trajectoryRemoveObject:(danmuItem *)object
{
    if ([_trajectoryArray2 containsObject:object]) {
        [_trajectoryArray2 removeObject:object];
    } else if ([_trajectoryArray3 containsObject:object]) {
        [_trajectoryArray3 removeObject:object];
    } else if ([_trajectoryArray4 containsObject:object]) {
        [_trajectoryArray4 removeObject:object];
    } else if ([_trajectoryArray5 containsObject:object]) {
        [_trajectoryArray5 removeObject:object];
    } else if ([_trajectoryArray6 containsObject:object]) {
        [_trajectoryArray6 removeObject:object];
    } else if ([_trajectoryArray7 containsObject:object]) {
        [_trajectoryArray7 removeObject:object];
    } else {
        
    }    
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (flag) {
        for (danmuItem *oldItem in self.subviews) {
            CABasicAnimation *animation =(CABasicAnimation *)[oldItem.layer animationForKey:@"danmu"];
            if ([anim isEqual:animation]) {
                [oldItem.layer removeAllAnimations];
                [oldItem removeFromSuperview];
                [self trajectoryRemoveObject:oldItem];
            }
        }
    }
}

- (void)requestHeadImage:(NSDictionary *)comment
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    NSDictionary *data = [[NSDictionary alloc]init];
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/show",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"]];
    [manager GET:str parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [responseObject objectForKey:@"data"];
        NSString *headImage = [dic objectForKey:@"avatar"];
        //        NSLog(@"成功%@",headImage);
        Comment *com = [[Comment alloc] init];
        com.avatar = headImage;
        com.comment = [comment valueForKey:@"content"];
        com.timeLine = [comment valueForKey:@"timeline"];
        [self createDanmuItem:com];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
